<script setup>
import {
    Management,
    Promotion,
    UserFilled,
    User,
    Crop,
    EditPen,
    SwitchButton,
    CaretBottom,
    List,
    Plus,
    Calendar,
    Document,
    Menu,
    Setting,
    Check,
    ChatDotRound,
    Warning,
    Collection,
    HomeFilled,
    Bell,
    Folder,
    School
} from '@element-plus/icons-vue'
import avatar from '@/assets/default.png'

import {userInfoService} from '@/api/user.js'
import useUserInfoStore from '@/stores/userInfo.js'
import {useTokenStore} from '@/stores/token.js'
import {useRouter} from 'vue-router'
import {ref, computed, onMounted, watch, onBeforeMount} from 'vue'
import {ElMessage,ElMessageBox} from 'element-plus'

const tokenStore = useTokenStore();
const userInfoStore = useUserInfoStore();
const router = useRouter();

// 检查用户是否已登录，未登录则跳转到登录页面
const checkLogin = () => {
    console.log('检查登录状态，当前token:', tokenStore.token);
    if (!tokenStore.token) {
        console.log('未检测到token，跳转到登录页');
        ElMessage.warning('请先登录');
        router.push('/login');
        return false;
    }
    return true;
};

// 在组件创建前检查登录状态
onBeforeMount(() => {
    // 立即检查登录状态
    if(!checkLogin()) {
        return;
    }
    // 如果有token才获取用户信息
    getUserInfo();
});

// 在组件挂载时再次检查登录状态（双重保障）
onMounted(() => {
    checkLogin();
});

// 监听token变化，当token被清除时自动跳转到登录页
watch(() => tokenStore.token, (newToken) => {
    console.log('token发生变化:', newToken);
    if (!newToken) {
        console.log('token被清除，跳转到登录页');
        router.push('/login');
    }
});

// 根据角色判断是否显示菜单项
const showMenuItem = (requiredRoles) => {
    const userRole = Number(userInfoStore.info.role); // 确保转换为数字
    const teacherStatus = userInfoStore.info.teacherStatus;
    const originalRole = userInfoStore.info.originalRole || userRole; // 获取原始角色
    const isGuest = userInfoStore.info.isGuest || false; // 判断是否为游客

    // 如果是游客，只允许访问游客可见的菜单
    if (isGuest) {
        // 如果当前页面是教师认证页面，只允许教师身份的游客访问
        if (router.currentRoute.value.path === '/teacher/certification') {
            return originalRole === 1;
        }
        // 游客不应该看到管理员功能和好友模块
        if (requiredRoles.includes(2)) {
            return false;
        }
        // 其他基本菜单根据角色判断
        return requiredRoles.includes(userRole);
    }

    // 如果是教师认证页面，允许原始角色为教师的用户访问
    if (router.currentRoute.value.path === '/teacher/certification') {
        return originalRole === 1;
    }

    // 如果是教师且需要审核通过
    if (userRole === 1 && requiredRoles.includes(1)) {
        // 检查是否需要教师审核
        const currentRoute = router.currentRoute.value;
        const requiresApproval = currentRoute.meta?.requiresTeacherApproval;
        
        if (requiresApproval && teacherStatus !== 1) {
            return false;
        }
    }
    
    return requiredRoles.includes(userRole);
};

//调用函数,获取用户详细信息
const getUserInfo = async()=>{
    // 再次检查token是否存在
    if (!tokenStore.token) {
        console.log('获取用户信息前检测到无token，跳转到登录页');
        ElMessage.warning('请先登录');
        router.push('/login');
        return;
    }
    
    try {
        console.log('开始获取用户信息');
        //调用接口
        let result = await userInfoService();
        console.log('获取用户信息成功:', result);
        //数据存储到pinia中
        userInfoStore.setInfo(result.data);
        // 同步更新 token store 中的角色
        tokenStore.setUserRole(Number(result.data.role));
    } catch (error) {
        console.error('获取用户信息失败:', error);
        // 如果获取用户信息失败，可能是token无效，跳转到登录页
        ElMessage.error('获取用户信息失败，请重新登录');
        tokenStore.removeToken();
        router.push('/login');
    }
}

//条目被点击后,调用的函数
const handleCommand = (command)=>{
    //判断指令
    if(command === 'logout'){
        //退出登录
        ElMessageBox.confirm(
        '您确认要退出吗?',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //退出登录
            console.log('用户确认退出登录');
            //1.清空pinia中存储的token以及个人信息
            tokenStore.removeToken()
            userInfoStore.removeInfo()

            //2.跳转到登录页面
            router.push('/login')
            ElMessage({
                type: 'success',
                message: '退出登录成功',
            })
            
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '用户取消了退出登录',
            })
        })
    }else{
        //路由
        router.push('/user/'+command)
    }
}

// 计算菜单项
const menuItems = computed(() => {
    const userRole = tokenStore.userRole
    const teacherStatus = userInfoStore.info.teacherStatus
    
    // 首页菜单项（保持单独定义，确保始终在最前面）
    const homeMenu = {
        path: '/home',
        title: '首页',
        icon: HomeFilled,
        id: 'home'
    }
    
    // 基础菜单项（所有角色都可以看到）
    const baseMenus = [
        {
            path: '/stream',
            title: 'AI助手',
            icon: ChatDotRound,
            id: 'ai'
        }
    ]

    // 非管理员可见的菜单
    const nonAdminBaseMenus = userRole === 0 ? [
        {
            path: '/tutoring/list',
            title: '家教列表',
            icon: List,
            id: 'tutoring-list'
        }
    ] : []

    // 教师认证菜单（仅待审核教师可见）
    const certificationMenu = userRole === 1 && teacherStatus !== 1 ? [
        {
            path: '/teacher/certification',
            title: '教师认证',
            icon: Check,
            id: 'certification'
        }
    ] : []

    // 教师家教菜单（仅已认证教师可见）
    const teacherTutoringMenu = userRole === 1 && teacherStatus === 1 ? [
        {
            path: '/tutoring/publish',
            title: '发布家教',
            icon: Plus,
            id: 'tutoring-publish'
        },
        {
            path: '/tutoring/manage',
            title: '家教管理',
            icon: Management,
            id: 'tutoring-manage'
        },
        {
            path: '/teacher/schedule',
            title: '课程安排',
            icon: Calendar,
            id: 'teacher-schedule'
        },
        {
            path: '/payment/records',
            title: '支付记录',
            icon: Document,
            id: 'payment-records-teacher'
        }
    ] : []

    // 学生家教菜单
    const studentTutoringMenu = userRole === 0 ? [
        {
            path: '/tutoring/booking',
            title: '我的预约',
            icon: Calendar,
            id: 'tutoring-booking'
        },
        {
            path: '/student/schedule',
            title: '课程安排',
            icon: Calendar,
            id: 'student-schedule'
        },
        {
            path: '/payment/records',
            title: '支付记录',
            icon: Document,
            id: 'payment-records-student'
        }
    ] : []

    // 学生和教师可见的菜单
    const lessonMenus = [
        {
            path: '/lesson/manage',
            title: '网课模块',
            icon: Document,
            id: 'lesson-manage'
        }
    ]

    // 管理员专属菜单
    const adminMenus = [
        {
            path: '/admin/teachers',
            title: '教师审核',
            icon: User,
            id: 'admin_teachers'
        },
        {
            path: '/admin/users',
            title: '用户管理',
            icon: User,
            id: 'admin_users'
        },
        {
            path: '/admin/announcement',
            title: '公告管理',
            icon: Bell,
            id: 'admin_announcement'
        },
        {
            path: '/admin/feedback',
            title: '反馈管理',
            icon: ChatDotRound,
            id: 'admin_feedback'
        },
        {
            path: '/lesson/category',
            title: '分类管理',
            icon: Folder,
            id: 'admin_category'
        },
        {
            path: '/admin/lesson',
            title: '网课管理',
            icon: Document,
            id: 'admin_lesson'
        },
        {
            path: '/admin/tutoring',
            title: '家教审核',
            icon: School,
            id: 'admin_tutoring'
        }
    ]

    // 根据角色返回对应的菜单项
    if (userRole === 2) {
        // 管理员只看到基础菜单和管理员菜单
        return [homeMenu, ...baseMenus, ...adminMenus]
    } else {
        // 学生和教师看到基础菜单和课程管理
        // 如果是教师且需要审核，显示认证菜单
        if (userRole === 1 && teacherStatus !== 1) {
            return [homeMenu, ...baseMenus, ...nonAdminBaseMenus, ...certificationMenu]
        }
        if (userRole === 1) {
            // 确保首页始终在最前面，教师家教相关菜单将使用下拉方式展示
            return [homeMenu, ...lessonMenus, ...baseMenus, ...nonAdminBaseMenus]
        }
        return [homeMenu, ...baseMenus, ...nonAdminBaseMenus, ...lessonMenus, ...studentTutoringMenu]
    }
})

</script>

<template>
    <el-container class="layout-container">
        <!-- 左侧菜单 -->
        <el-aside width="200px">
            <div class="el-aside__logo"></div>
            <el-menu active-text-color="#ffd04b" background-color="#232323" text-color="#fff"
                router>
                <el-menu-item v-for="item in menuItems" :key="item.id" :index="item.path">
                    <el-icon>
                        <component :is="item.icon" />
                    </el-icon>
                    <span>{{item.title}}</span>
                </el-menu-item>

                <!-- 好友模块子菜单 -->
                <el-sub-menu index="/friend-module" v-if="tokenStore.userRole !== 2 && !userInfoStore.info.isGuest">
                    <template #title>
                        <el-icon>
                            <UserFilled />
                        </el-icon>
                        <span>好友模块</span>
                    </template>
                    <el-menu-item index="/friend">
                        <el-icon>
                            <User />
                        </el-icon>
                        <span>好友列表</span>
                    </el-menu-item>
                    <el-menu-item index="/cm">
                        <el-icon>
                            <ChatDotRound />
                        </el-icon>
                        <span>聊天</span>
                    </el-menu-item>
                </el-sub-menu>

                <!-- 作业模块子菜单（仅学生可见） -->
                <el-sub-menu index="/homework-module" v-if="tokenStore.userRole === 0 && !userInfoStore.info.isGuest">
                    <template #title>
                        <el-icon>
                            <Document />
                        </el-icon>
                        <span>作业模块</span>
                    </template>
                    <el-menu-item index="/homework/student">
                        <el-icon>
                            <Document />
                        </el-icon>
                        <span>我的作业</span>
                    </el-menu-item>
                    <el-menu-item index="/student/mistake-book">
                        <el-icon>
                            <Warning />
                        </el-icon>
                        <span>错题本</span>
                    </el-menu-item>
                </el-sub-menu>

                <!-- 作业模块子菜单（仅教师可见） -->
                <el-sub-menu index="/teacher-homework-module" v-if="tokenStore.userRole === 1 && userInfoStore.info.teacherStatus === 1 && !userInfoStore.info.isGuest">
                    <template #title>
                        <el-icon>
                            <Document />
                        </el-icon>
                        <span>作业模块</span>
                    </template>
                    <el-menu-item index="/homework/teacher">
                        <el-icon>
                            <Document />
                        </el-icon>
                        <span>作业管理</span>
                    </el-menu-item>
                    <el-menu-item index="/teacher/knowledge-points">
                        <el-icon>
                            <Collection />
                        </el-icon>
                        <span>知识点管理</span>
                    </el-menu-item>
                </el-sub-menu>
                
                <!-- 家教模块子菜单（仅已认证教师可见） -->
                <el-sub-menu index="/tutoring-module" v-if="tokenStore.userRole === 1 && userInfoStore.info.teacherStatus === 1 && !userInfoStore.info.isGuest">
                    <template #title>
                        <el-icon>
                            <School />
                        </el-icon>
                        <span>家教模块</span>
                    </template>
                    <el-menu-item index="/tutoring/list">
                        <el-icon>
                            <List />
                        </el-icon>
                        <span>家教列表</span>
                    </el-menu-item>
                    <el-menu-item index="/tutoring/publish">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        <span>发布家教</span>
                    </el-menu-item>
                    <el-menu-item index="/tutoring/manage">
                        <el-icon>
                            <Management />
                        </el-icon>
                        <span>家教管理</span>
                    </el-menu-item>
                    <el-menu-item index="/teacher/schedule">
                        <el-icon>
                            <Calendar />
                        </el-icon>
                        <span>课程安排</span>
                    </el-menu-item>
                    <el-menu-item index="/payment/records">
                        <el-icon>
                            <Document />
                        </el-icon>
                        <span>支付记录</span>
                    </el-menu-item>
                </el-sub-menu>

                <!-- 个人中心菜单 -->
                <el-sub-menu index="/user">
                    <template #title>
                        <el-icon>
                            <UserFilled />
                        </el-icon>
                        <span>个人中心</span>
                    </template>
                    <el-menu-item index="/user/info">
                        <el-icon>
                            <User />
                        </el-icon>
                        <span>基本资料</span>
                    </el-menu-item>
                    <el-menu-item index="/user/avatar">
                        <el-icon>
                            <Crop />
                        </el-icon>
                        <span>更换头像</span>
                    </el-menu-item>
                    <el-menu-item index="/user/resetPassword">
                        <el-icon>
                            <EditPen />
                        </el-icon>
                        <span>重置密码</span>
                    </el-menu-item>
                </el-sub-menu>
            </el-menu>
        </el-aside>
        <!-- 右侧主区域 -->
        <el-container>
            <!-- 头部区域 -->
            <el-header>
                <div>名称：<strong>{{userInfoStore.info.username}}</strong></div>
                <el-dropdown placement="bottom-end" @command="handleCommand">
                    <span class="el-dropdown__box">
                        <el-avatar :src="userInfoStore.info.userPic? userInfoStore.info.userPic:avatar" />
                        <el-icon>
                            <CaretBottom />
                        </el-icon>
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="info" :icon="User">基本资料</el-dropdown-item>
                            <el-dropdown-item command="avatar" :icon="Crop">更换头像</el-dropdown-item>
                            <el-dropdown-item command="resetPassword" :icon="EditPen">重置密码</el-dropdown-item>
                            <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </el-header>
            <!-- 中间区域 -->
            <el-main>
                <router-view></router-view>
            </el-main>
            <!-- 底部区域 -->
            <el-footer></el-footer>
        </el-container>
    </el-container>
</template>

<style lang="scss" scoped>
.layout-container {
    height: 100vh;

    .el-aside {
        background-color: #232323;

        &__logo {
            height: 120px;
            background: url('@/assets/image2.png') no-repeat center / 120px auto;
        }

        .el-menu {
            border-right: none;
        }
    }

    .el-header {
        background-color: #fff;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .el-dropdown__box {
            display: flex;
            align-items: center;

            .el-icon {
                color: #999;
                margin-left: 10px;
            }

            &:active,
            &:focus {
                outline: none;
            }
        }
    }

    .el-footer {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        color: #666;
    }
}
</style>